import pymysql
import datetime
import random

# 连接数据库
connection = pymysql.connect(host='localhost',
                             user='root',
                             password='200206',
                             database='Temperature_Control_System',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)

try:
    with connection.cursor() as cursor:
        # SQL 插入语句
        sql = "INSERT INTO temperature_log (temperature, log_time) VALUES (%s, %s)"
        
        # 初始温度和日期
        start_temp = 20.0
        end_temp = -10.0
        start_date = datetime.date(2024, 10, 1)
        end_date = datetime.date(2024, 11, 1)
        current_temp = start_temp
        current_date = start_date
        
        # 循环插入数据
        while current_date < end_date:  # 确保不包括结束日期
            for hour in range(24):
                for ten_minute in range(6):  # 每小时6个十分钟间隔
                    # 计算当前时间
                    current_time = datetime.datetime.combine(current_date, datetime.time()) + datetime.timedelta(hours=hour, minutes=ten_minute*10)
                    
                    # 计算温度变化，确保变化不超过0.5度
                    days_elapsed = (current_date - start_date).days + (hour + ten_minute*10/60.0)/24.0
                    change = (end_temp - start_temp) * days_elapsed / ((end_date - start_date).days)
                    new_temp = start_temp + change
                    
                    # 添加随机小数部分
                    random_decimal = round(random.uniform(-0.25, 0.25), 2)
                    new_temp += random_decimal
                    
                    # 限制温度范围
                    new_temp = max(end_temp, min(new_temp, start_temp))
                    
                    # 插入数据
                    cursor.execute(sql, (new_temp, current_time))
                    connection.commit()
            
            # 增加日期
            current_date += datetime.timedelta(days=1)

finally:
    connection.close()